package org.gwt.pluginframework.plugin;

import java.util.ArrayList;
import java.util.List;

import org.gwt.pluginframework.common.Plugin;
import org.gwt.pluginframework.common.event.IPluginEvent;
import org.gwt.pluginframework.common.event.PluginEvent;
import org.gwt.pluginframework.common.event.PluginEventHandler;

import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.TabPanelEvent;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.TabItem;
import com.extjs.gxt.ui.client.widget.TabPanel;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Widget;

public class TabManagerPlugin extends Plugin implements PerspectiveCenterExtension {

	private static final long serialVersionUID = 255426371905034761L;

	protected TabPanel rootPanel;

	protected List<Tabbable> rawItems;
	
	public TabManagerPlugin() {
		rawItems = new ArrayList<Tabbable>();
	}
	
	public void setupManifest() {
		manifest.setName("TabManager");
		manifest.setVersion("1.0");
	}

	@Override
	public void onInitialize() {
		registerEventHandler(new PluginEventHandler(CustomEvents.START_TAB_EVENT) {
			public void handle(IPluginEvent event) {
				TabItem item = (TabItem) event.getParameters().get("tabItem");
				rootPanel.add(item);
				rootPanel.setSelection(item);
				
				// FIX panel resizes problem with first tabItem
				if (rootPanel.getItemCount() < 2) {
					((LayoutContainer) rootPanel.getParent()).layout();
				}
			}
		});
		registerEventHandler(new PluginEventHandler(CustomEvents.FOCUS_TAB_EVENT) {
			public void handle(IPluginEvent event) {
				TabItem item = (TabItem) event.getParameters().get("tabItem");
				rootPanel.setSelection(item);				
			}
		});
	}
	
	@Override
	public void onStart() {
		rootPanel = new TabPanel();
		rootPanel.setResizeTabs(true);
		rootPanel.setAnimScroll(true);
		rootPanel.setTabScroll(true);

		rootPanel.addListener(Events.Select,
				new Listener<TabPanelEvent>() {
					public void handleEvent(TabPanelEvent tpe) {
						TabItem item = tpe.getItem();
						//Info.display("Selection Changed",
						//		"The '{0}' item was selected", item.getText());
						
						manager.dispatch(new PluginEvent(
								CustomEvents.FOCUS_ITEM_EVENT, TabManagerPlugin.this, 
								new String[] {"name"}, new Object[] {item.getText()}));
					}
				});
		rootPanel.addListener(Events.SelectionChange, new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				Window.alert("WTF");				
			}
		});
	}

	public Widget getWidget() {
		return rootPanel;
	}
}
